package com.niuwa.p2p.service.impl.redenvelope;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.niuwa.p2p.core.utils.DateUtil;
import com.niuwa.p2p.core.utils.DictConstant;
import com.niuwa.p2p.core.utils.SequenceEnum;
import com.niuwa.p2p.dao.customer.CustomerDao;
import com.niuwa.p2p.dao.redenvelope.RedEnvelopeDao;
import com.niuwa.p2p.dao.redenvelope.RedEnvelopeRuleDao;
import com.niuwa.p2p.dao.redenvelope.RedRangeDao;
import com.niuwa.p2p.entity.customer.Customer;
import com.niuwa.p2p.entity.redenvelope.RedEnvelope;
import com.niuwa.p2p.entity.redenvelope.RedEnvelopeRule;
import com.niuwa.p2p.service.redenvelope.IRedEnevlopeGenerateService;
import com.niuwa.p2p.service.sequence.ISequenceService;

@Service
public class RedEnevlopeGenerateServiceImpl implements IRedEnevlopeGenerateService{

	private Logger log = Logger.getLogger(RedEnevlopeGenerateServiceImpl.class);
	@Autowired
	private RedEnvelopeRuleDao redEnvelopeRuleDao;
	@Autowired
	private RedEnvelopeDao redEnvelopeDao;
	
	@Autowired
	private CustomerDao customerDao;
	
	@Autowired
	ISequenceService sequenceService;

	@Autowired
	private RedRangeDao redRangeDao;
	
	@Override
	public void generateByRegister(Customer customer) {
		//查询自动创建规则，触发动作为注册，已生效的规则,能使用客户
		List<RedEnvelopeRule> list = redEnvelopeRuleDao.selectByMap(getParamMap(DictConstant.RED_RULE_STATUS.HAD_VALID.getCode(), DictConstant.RULE_TRI_ACTION.REGISTER.getCode(),customer.getCustKind()));
		if(list != null && list.size() > 0){
			for(RedEnvelopeRule rer : list){
				//根据规则生成红包
				RedEnvelope redEnvelope = initCommProperty(rer);
				BigDecimal amount = rer.getAmount() == null ? new BigDecimal(0):rer.getAmount();
				redEnvelope.setAmount(amount.divide(new BigDecimal(1), 0, BigDecimal.ROUND_HALF_UP).intValue());//红包金额
				String triggerType = rer.getTriggerType();//触发人====设置持有人
				boolean result = setRedOwner(redEnvelope, triggerType, customer.getLoginName(), customer.getId(), customer.getReferee());
				if(result){
					redEnvelopeDao.insert(redEnvelope);
				}
			}
		}
	}

	
	
	@Override
	public void generateByInvest(Long custId, BigDecimal investAmount) {
		Customer customer = customerDao.selectByCustId(custId);
		if(customer != null){
			List<RedEnvelopeRule> list = redEnvelopeRuleDao.selectByMap(getParamMap(DictConstant.RED_RULE_STATUS.HAD_VALID.getCode(),DictConstant.RULE_TRI_ACTION.INVEST.getCode(),customer.getCustKind()));
			if(list != null && list.size() > 0){
				for(RedEnvelopeRule rer : list){
					BigDecimal overAmount = rer.getOverAmount();
					if(investAmount.compareTo(overAmount) < 0){//投资金额小于投资满额
						continue;
					}
					RedEnvelope redEnvelope = initCommProperty(rer);
					//设置金额
					String amtType = rer.getAmtType();//红包金额类型
					if(DictConstant.RED_AMOUNT_TYPE.FIX.getCode().equals(amtType)){//固定
						BigDecimal amount = rer.getAmount() == null ? new BigDecimal(0):rer.getAmount();
						redEnvelope.setAmount(amount.divide(new BigDecimal(1), 0, BigDecimal.ROUND_HALF_UP).intValue());//红包金额
					}else if(DictConstant.RED_AMOUNT_TYPE.PER.getCode().equals(amtType)){//比例
						BigDecimal amount = rer.getAmountPercent()==null ? new BigDecimal(0) : new BigDecimal(rer.getAmountPercent()).divide(new BigDecimal(100)).multiply(investAmount);
						redEnvelope.setAmount(amount.divide(new BigDecimal(1), 0, BigDecimal.ROUND_HALF_UP).intValue());
					}else if(DictConstant.RED_AMOUNT_TYPE.AREA.getCode().equals(amtType)){//区间
						BigDecimal amount = getAmountByInvestAmount(rer.getRuleNo(), investAmount);
						if(amount != null)
							redEnvelope.setAmount(amount.divide(new BigDecimal(1), 0, BigDecimal.ROUND_HALF_UP).intValue());
					}
					String triggerType = rer.getTriggerType();//触发人====设置持有人
					String frequecy = rer.getFrequecy();
					boolean result = setRedOwner(redEnvelope, triggerType, customer.getLoginName(), custId, customer.getReferee());
					if(result){
						String triggerAction =  redEnvelope.getTriggerAction();
						if(DictConstant.TRIGGER_PERSON.RECOMMEND.getCode().equals(triggerAction)){//给推荐人添加
							if(DictConstant.RED_FREQUENCY.ONCE.getCode().equals(frequecy)){//-次
								boolean isFrist = isFristTimeGen(rer.getRuleNo(), redEnvelope.getCustId());
								if(isFrist)
									redEnvelopeDao.insert(redEnvelope);
							}else if(DictConstant.RED_FREQUENCY.EVERY_TIME.getCode().equals(frequecy)){//每次
								redEnvelopeDao.insert(redEnvelope);
							}
						}else{//给自己
							if(DictConstant.RED_FREQUENCY.ONCE.getCode().equals(frequecy)){
								boolean isFrist = isFristTimeGen(rer.getRuleNo(), custId);
								if(isFrist)
									redEnvelopeDao.insert(redEnvelope);
							}else if(DictConstant.RED_FREQUENCY.EVERY_TIME.getCode().equals(frequecy)){
								redEnvelopeDao.insert(redEnvelope);
							}
						}
					}
				}
			}
		}
	}

	@Override
	public void generateByOpenAccount(Long custId) {
		Customer customer = customerDao.selectByCustId(custId);
		if(customer != null){
			//查询自动创建规则，触发动作为注册，已生效的规则,能使用客户
			List<RedEnvelopeRule> list = redEnvelopeRuleDao.selectByMap(getParamMap(DictConstant.RED_RULE_STATUS.HAD_VALID.getCode(), DictConstant.RULE_TRI_ACTION.OPEN_ACCT.getCode(),customer.getCustKind()));
			if(list != null && list.size() > 0){
				for(RedEnvelopeRule rer : list){
					//根据规则生成红包
					RedEnvelope redEnvelope = initCommProperty(rer);
					BigDecimal amount = rer.getAmount() == null ? new BigDecimal(0):rer.getAmount();
					redEnvelope.setAmount(amount.divide(new BigDecimal(1), 0, BigDecimal.ROUND_HALF_UP).intValue());//红包金额
					String triggerType = rer.getTriggerType();//触发人====设置持有人
					String frequecy = rer.getFrequecy();
					boolean result = setRedOwner(redEnvelope, triggerType, customer.getLoginName(), custId, customer.getReferee());
					if(result){
						String triggerAction =  redEnvelope.getTriggerAction();
						if(DictConstant.TRIGGER_PERSON.RECOMMEND.getCode().equals(triggerAction)){//给推荐人添加
							if(DictConstant.RED_FREQUENCY.ONCE.getCode().equals(frequecy)){//-次
								boolean isFrist = isFristTimeGen(rer.getRuleNo(), redEnvelope.getCustId());
								if(isFrist)
									redEnvelopeDao.insert(redEnvelope);
							}else if(DictConstant.RED_FREQUENCY.EVERY_TIME.getCode().equals(frequecy)){//每次
								redEnvelopeDao.insert(redEnvelope);
							}
						}else{//给自己
							if(DictConstant.RED_FREQUENCY.ONCE.getCode().equals(frequecy)){
								boolean isFrist = isFristTimeGen(rer.getRuleNo(), custId);
								if(isFrist)
									redEnvelopeDao.insert(redEnvelope);
							}else if(DictConstant.RED_FREQUENCY.EVERY_TIME.getCode().equals(frequecy)){
								redEnvelopeDao.insert(redEnvelope);
							}
						}
					}
				}
			}
		}
	}
	
	/**
	 * 是否第一次通过规则给用户生成红包
	 * @param ruleNo
	 * @param custId
	 * @return
	 */
	private boolean isFristTimeGen(String ruleNo,long custId){
		boolean result = false;
		Map<String,Object>  map = new HashMap<String,Object>();
		map.put("ruleNo", ruleNo);
		map.put("custId", custId);
		List<RedEnvelope> redEnvelopeList = redEnvelopeDao.alreadyGenByRule(map);
		if(redEnvelopeList == null || redEnvelopeList.size() == 0){
			result = true;
		}
		return result;
	}
	/**
	 * 是否可以设置红包用户名称和id
	 * @param redEnvelope
	 * @param triggerType
	 * @param loginName
	 * @param custId
	 * @param referee
	 * @return
	 */
	private boolean setRedOwner(RedEnvelope redEnvelope,String triggerType,String loginName,long custId,long referee){
		boolean result = true;
		if(DictConstant.TRIGGER_PERSON.OWNER.getCode().equals(triggerType)){//自己
			redEnvelope.setCustName(loginName);//持有人名称
			redEnvelope.setCustId(custId);//持有人id
		}else if(DictConstant.TRIGGER_PERSON.RECOMMEND.getCode().equals(triggerType)){//推荐好友
			if(referee != 0){
				Customer c = customerDao.findCustomerById(String.valueOf(referee));
				if(c != null){//推荐人存在
					redEnvelope.setTriggerAction(DictConstant.TRIGGER_ACTION.RECOMMEND.getCode());
					redEnvelope.setCustId(c.getId());
					redEnvelope.setCustName(c.getLoginName());
				}else{
					result = false;
				}
			}else{
				result = false;
			}
		}
		return result;
	}
	/**
	 * 将参数封装成map对象
	 * @param status
	 * @param triggerAction
	 * @param availCustomer
	 * @return
	 */
	private Map<String,String> getParamMap(String status,String triggerAction,String availCustomer){
		Map<String,String> paramMap = new HashMap<String,String>();
		paramMap.put("status", status);
		paramMap.put("triggerAction", triggerAction);
		paramMap.put("availCustomer", availCustomer);
		return paramMap;
	}
	
	/**
	 * 获取红包兑换码
	 * @return
	 */
	private String getRedExchangeNo(){
		String result = "";
		try {
			result = sequenceService.getCompleteSequenceBySeqKey(SequenceEnum.HB.getCode(), SequenceEnum.HB.getLength());
		} catch (Exception e) {
			log.info("生成红包兑换码失败!");
		}
		return result;
		
	}
	/**
	 * 根据投资金额获取奖励金额
	 * @return
	 */
	private BigDecimal getAmountByInvestAmount(String ruleNo,BigDecimal investAmount){
		BigDecimal result = new BigDecimal(0);
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("ruleNo", ruleNo);
		map.put("amount", investAmount);
		BigDecimal amount = redRangeDao.getAmountByInvestAmount(map);
		if(amount != null)
			result = amount;
		return result;
	}
	/**
	 * 通过红包模板规则，生成红包对象
	 * @param rer
	 * @return
	 */
	private RedEnvelope initCommProperty(RedEnvelopeRule rer){
		RedEnvelope redEnvelope = new RedEnvelope();
		redEnvelope.setExchangeNo(getRedExchangeNo());//兑换码
		redEnvelope.setRuleNo(rer.getRuleNo());//红包规则编号
		redEnvelope.setName(rer.getRedEnvelopeName());//红包名称
		redEnvelope.setStartDate(new Date());//红包生效日期--设置为当前时间
		redEnvelope.setCreateTime(new Date());//红包创建时间
		String validTermType = rer.getValidTermType();//设置红包失效日期
		if(DictConstant.RED_VALID_TERM.DAYS.getCode().equals(validTermType)){//天数
			redEnvelope.setEndDate(DateUtil.addDays(new Date(), rer.getValidTermDays()));
		}else if(DictConstant.RED_VALID_TERM.ONE_WEEK.getCode().equals(validTermType)){//一周
			redEnvelope.setEndDate(DateUtil.addDays(new Date(), 7));
		}else if(DictConstant.RED_VALID_TERM.ONE_MONTH.getCode().equals(validTermType)){//一月
			redEnvelope.setEndDate(DateUtil.addMonths(new Date(), 1));
		}else if(DictConstant.RED_VALID_TERM.THREE_MONTH.getCode().equals(validTermType)){//3个月
			redEnvelope.setEndDate(DateUtil.addMonths(new Date(), 3));
		}else if(DictConstant.RED_VALID_TERM.EVER.getCode().equals(validTermType)){//永久有效【生效时间+50年】
			redEnvelope.setEndDate(DateUtil.addYears(new Date(),50));
		}
		
		redEnvelope.setIssueDate(new Date());//红包发放日期
		redEnvelope.setStatus(DictConstant.RED_USE_STATUS.NO_USE.getCode());//红包状态：未使用
		redEnvelope.setConsumedPercent(rer.getConsumerPercent());//比例
		redEnvelope.setAvailActions(rer.getAvailActions());//使用范围
		redEnvelope.setAvailPlatform(rer.getAvailPlatform());//使用平台
		redEnvelope.setTriggerAction(rer.getTriggerAction());//生成动作（触发动作）
		return redEnvelope;
	}
	public static void main(String[] args) {
		BigDecimal b = new BigDecimal(10.5);
		System.out.println(b.divide(new BigDecimal(1), 0, BigDecimal.ROUND_HALF_UP).intValue());
	}
}
